package org.sanguine.tests.protei.springapp.mvc.services;

import org.sanguine.tests.protei.springapp.mvc.NotValidEntityException;
import org.sanguine.tests.protei.springapp.mvc.dao.MySQLEntityDAO;
import org.sanguine.tests.protei.springapp.mvc.models.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import java.util.List;
import java.util.Set;

/**
 * Created by alex on 25.02.14.
 * Author: Alex Kuznetsov
 */

/**
 * Сервисный класс для обработки и валидации CRUD-запросов для элемента типа Goods
 */
@org.springframework.stereotype.Service
@Scope(value = "singleton")
public class GoodsService implements Service<Goods> {

    @Autowired
    Validator validator;

    private Set<ConstraintViolation<Goods>> constraintViolations;

    private MySQLEntityDAO<Goods> dao;

    @Autowired
    @Qualifier("JndiMySQLDao")
    public void setDAO(MySQLEntityDAO<Goods> entityDAO) {
        dao = entityDAO;
        dao.setEntityType(Goods.class);
    }

    @Override
    public Goods getById(String id) {
        return (dao == null) ? null : dao.findByKey(id);
    }

    @Override
    public Goods create(Goods newGoods) {
        if (isValid(newGoods)) return (dao == null) ? null : dao.addEntity(newGoods);
        throw new NotValidEntityException(getValidatorMessage());
    }

    @Override
    public boolean deleteById(String id) {
        return (dao == null) ? false : dao.removeEntity(id);
    }

    @Override
    public boolean updateById(String id, Goods goods) {
        if (dao == null) return false;
        goods.setId(id);
        if (isValid(goods)) return dao.updateEntity(goods);
        throw new NotValidEntityException(getValidatorMessage());
    }

    private String getValidatorMessage() {
        if (constraintViolations == null) return "";
        StringBuffer buf = new StringBuffer();
        for (ConstraintViolation<Goods> c : constraintViolations) {
            buf.append(String.format("Invalid value of %s: %s. Reason: %s\n", c.getPropertyPath().toString(),
                                    c.getInvalidValue().toString(),
                                    c.getMessage()));
        }
        return buf.toString();
    }

    private boolean isValid(Goods goods) {
        if (validator != null) {
            Set<ConstraintViolation<Goods>> constraintViolations = validator.validate(goods);
            if (constraintViolations.size() != 0) {
                this.constraintViolations = constraintViolations;
                return false;
            }
        }
        this.constraintViolations = null;
        return true;
    }

    @Override
    public boolean getAll(int page, int length, List<Goods> list) {
        return (dao == null) ? false : dao.findAll(page, length, list);
    }
}
